package com.sh.sales.happysales.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.sh.sales.happysales.app.AppContext;
import com.sh.sales.happysales.app.utils.LoginUtil;
import com.sh.sales.happysales.base.BaseActivity;
import com.sh.sales.happysales.config.Constant;
import com.sh.polymedicine.happysale.net.entity.UserToken;
import com.sh.sales.happysales.service.LoginObsever;
import com.sh.sales.happysales.service.WechatInLunchObserable;
import com.sh.polymedicine.happysale.result.UserInfoResult;
import com.sh.sales.happysales.ui.activity.BindPhoneActivity;
import com.sh.sales.happysales.ui.activity.ContentActivity;
import com.sh.sales.happysales.ui.activity.PerfectInfoActivity;
import com.sh.sales.happysales.view.NewToast;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import rx.Subscriber;


/**
 * Created by zhouyucheng on 2017/8/14.
 */

public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler, LoginObsever {
    private String TAG = "WXEntryActivity";
    private IWXAPI mWeixinAPI;
    private static Subscriber<UserToken> mUserSubscriber;
    private static Subscriber<UserInfoResult> mUserInfoSubscriber;
    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case Constant.GET_WEIXIN_DATA_FAIl:
                    NewToast.makeText(WXEntryActivity.this, "拉取信息失败", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case Constant.GET_WEIIN_DATA_NULL:
                    NewToast.makeText(WXEntryActivity.this, "拉取信息为空", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case Constant.GET_WEIIN_DATA_CANCLE:
                    NewToast.makeText(WXEntryActivity.this, "拉取微信取消", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case Constant.GET_WEIIN_DATA_DENIED:
                    NewToast.makeText(WXEntryActivity.this, "拉取微信拒绝", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case Constant.GET_WEIIN_DATA_OTHER:
                    NewToast.makeText(WXEntryActivity.this, "拉取微信未知错误", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case Constant.GET_USERINFO_DATA_FAIl:
                    NewToast.makeText(WXEntryActivity.this, "拉取用户信息错误", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case Constant.GET_USERINFO_DATA_NULL:
                    finish();
                    NewToast.makeText(WXEntryActivity.this, "拉取用户信息为空", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLoginObserable.registerObserver(this);
        mWeixinAPI = AppContext.getIwxapi();
        mWeixinAPI.handleIntent(this.getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mWeixinAPI.handleIntent(intent, this);//必须调用此句话
    }


    //微信发送的请求将回调到onReq方法
    @Override
    public void onReq(BaseReq req) {
        Log.i(TAG, "onReq: onReq");
    }

    //发送到微信请求的响应结果
    @Override
    public void onResp(BaseResp resp) {
        Log.i(TAG, "onResp: " + resp.errCode);
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                SendAuth.Resp regResp = (SendAuth.Resp) resp;
                WechatInLunchObserable.getInstance().testShow(regResp.code + "\n" + regResp.country + "\n" + regResp.lang + "\n" +
                        regResp.state + "\n" + regResp.url);
                Log.i(TAG, "onResp: " + "======================");
                Log.i(TAG, "onResp: " + regResp.code);
                UserToken m = new UserToken();
                m.setCode(regResp.code);
                LoginUtil.getInstance().catchUserInfo(m, WXEntryActivity.this, 1);
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Log.i(TAG, "onResp:ERR_USER_CANCEL ");
                mhandler.sendEmptyMessage(Constant.GET_WEIIN_DATA_CANCLE);
                //发送取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Log.i(TAG, "onResp:ERR_AUTH_DENIED ");
                mhandler.sendEmptyMessage(Constant.GET_WEIIN_DATA_DENIED);
                //发送被拒绝
                break;
            default:
                //发送返回
                mhandler.sendEmptyMessage(Constant.GET_WEIIN_DATA_OTHER);
                Log.i(TAG, "onResp: " + resp.errCode);
                break;
        }
    }

//    private void catchUserInfo(String code) {
//        //  String code = "021GZB0S04nqla2kGu3S0iNq0S0GZB0h";
//        final String deviceId = getIMEI();
//        Log.i(TAG, "catchUserInfo: " + deviceId);
//        if (mUserSubscriber != null) {
//            if (!mUserSubscriber.isUnsubscribed()) {
//                mUserSubscriber.unsubscribe();
//            }
//        }
//        mUserSubscriber = new Subscriber<UserToken>() {
//            @Override
//            public void onCompleted() {
//
//            }
//            @Override
//            public void onError(Throwable e) {
//                Log.d(TAG, "getHealthyVodChannelInfo onError" + e);
//            }
//
//            @Override
//            public void onNext(UserToken mUserToken) {
//                if (mUserToken != null) {
//                    String accessToken = mUserToken.getAccessToken();
//                    String reflashToken = mUserToken.getReflashToken();
//                    String signKey = mUserToken.getSignKey();
//                    userId = mUserToken.getUserId();
//                    mPreferenceUtil.saveString("accessToken", accessToken);
//                    mPreferenceUtil.saveString("reflashToken", reflashToken);
//                    mPreferenceUtil.saveString("signKey", signKey);
//                    mPreferenceUtil.saveInt("userId", userId);
//                    //accessToken|userId|reflashToken|deviceId
//                    String userSign = IDEACode.getSignedData(accessToken, userId, reflashToken, deviceId, "123456789");
//                    mPreferenceUtil.saveString("userSign", userSign);
//                    Log.i(TAG, "onNext: ========================");
//                    Log.i(TAG, "onNextaccessToken: " + mPreferenceUtil.getString("accessToken", ""));
//                    Log.i(TAG, "onNextreflashToken: " + mPreferenceUtil.getString("reflashToken", ""));
//                    Log.i(TAG, "onNextsignKey: " + mPreferenceUtil.getString("signKey", ""));
//                    Log.i(TAG, "onNextuserId: " + mPreferenceUtil.getString("userId", ""));
//                    Log.i(TAG, "onNextuserSign: " + mPreferenceUtil.getString("userSign", ""));
//                    getMyInfo(userSign, userId);
//                } else {
//
//                }
//            }
//        };
//        HappySaleManager.getInstence().weixinLogin(code, deviceId, mUserSubscriber).subscribe(mUserSubscriber);
//    }
//
//    private void getMyInfo(String userSign, int userId) {
//        if (mUserInfoSubscriber != null) {
//            if (!mUserInfoSubscriber.isUnsubscribed()) {
//                mUserInfoSubscriber.unsubscribe();
//            }
//        }
//        mUserInfoSubscriber = new Subscriber<UserInfoResult>() {
//            @Override
//            public void onCompleted() {
//
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                Log.i(TAG, "onError: " + e);
//            }
//
//            @Override
//            public void onNext(UserInfoResult mUserInfoResult) {
//                if (mUserInfoResult != null) {
//                    LocalUserInfoUtils.insertUserInfoResult(mUserInfoResult);
//                    if (null==mUserInfoResult.getMobile()) {
//                        enterActivity(1);
//                    } else {
//                        if ("0".equals(mUserInfoResult.getRole()) || "-1".equals(mUserInfoResult.getRole())) {
//                            enterActivity(2);
//                        } else {
//                            enterActivity(3);
//                        }
//                    }
//                } else {
//
//                }
//            }
//        };
//        HappySaleManager.getInstence().userInfo(userId + "", userSign, mUserInfoSubscriber).subscribe(mUserInfoSubscriber);
//
//
//    }


    private void enterActivity(int type) {
        Intent mIntent = new Intent();
        switch (type) {
            case 1:
                mIntent.setClass(this, BindPhoneActivity.class);
                break;
            case 2:
                mIntent.setClass(this, PerfectInfoActivity.class);
                break;
            case 3:
                mIntent.setClass(this, ContentActivity.class);
                break;
        }
        startActivity(mIntent);
        this.finish();
    }


//    private String getIMEI() {
//        TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
//        String szImei = TelephonyMgr.getImei();
//        return szImei;
//    }

    @Override
    public void refreshUserSign(int intentPosition) {
        enterActivity(intentPosition);
    }

//    public static String getLocalMacAddressFromWifiInfo() {
//        WifiManager wifi = (WifiManager) AppContext.getInstance().getSystemService(Context.WIFI_SERVICE);
//        WifiInfo info = wifi.getConnectionInfo();
//        return info.getMacAddress();
//    }


    @Override
    protected void onDestroy() {
        mLoginObserable.unregisterObserver(this);
        super.onDestroy();
    }
}
